<template>
  <div class="file-box">
    <div class="no-kaifa">
      <img src="../../assets/images/nokaifa.png" />
      <span>该功能暂未开放、敬请期待~</span>
    </div>

    <!-- <div class="title">
      <div class="left-title"></div>
      <span class="title-coutent">发布文档</span>
    </div>
    <div v-if="route.query.state === 'device'" class="next-button">
      <a-button class="next" @click="onPublic(1)"> 发布 </a-button>
      <a-button v-if="positionTypes !== 2" class="save" @click="onPublic(2)">定时发布</a-button>
      <a-button class="save" @click="onPublic(3)">保存草稿</a-button>
    </div>
    <div v-else class="next-button">
      <a-button v-if="route.query.state !== '草稿箱修改'" class="next" @click="onPublic('to')">
        下一步
      </a-button>
      <a-button class="save" @click="onPublic">保存草稿</a-button>
    </div> -->
    <!-- 上传文档 -->
    <!-- <Form class="form" name="basic" autocomplete="off">
      <Form.Item
        label="上传文档"
        name="uploadFile"
        :rules="[{ required: true, validator: checkPic }]"
      >
        <Upload
          v-if="coverFileList.length < 1"
          action=""
          list-type="picture-card"
          :file-list="coverFileList"
          accept=".pdf"
          :remove="deleteFiles"
          :custom-request="customRequest"
          @change="handleChange"
        > -->
    <!-- 文档列表 -->
    <!-- <div>
            <img class="upload-icon" src="../../../src/assets/icons/images/upload.png" />
            <span class="tip">支持格式PDF 单个文档大小≤50M</span>
          </div>
        </Upload> -->
    <!-- 分页 -->
    <!-- <div v-else class="exhibition-Pdf-box">
          <div v-for="(item, index) in pageList" :key="item.index" class="exhibition-Pdf">
            <img v-if="item.state" class="pdf-img" :src="item.url" />
            <div class="car">
              <div v-if="item.state" class="pager">
                <div
                  class="pager-left"
                  :class="currentPage === 1 ? 'prohibit' : null"
                  @click="currentPage !== 1 ? pageReduce(index) : null"
                >
                  <i class="ifont-wid-Calendar_icon_month_left"></i>
                </div>
                <div class="number">{{ currentPage }}/{{ filePage }}</div>
                <div
                  class="pager-right"
                  :class="currentPage === filePage ? 'prohibit' : null"
                  @click="currentPage !== filePage ? pageAdd(index) : null"
                >
                  <i class="ifont-wid-Calendar_icon_month_right"></i>
                </div>
              </div>
            </div>
          </div>
          <div v-if="!loading" class="delete">
            <img
              src="../../assets/images/Upload_icon_dete.png"
              alt=""
              @click="dialog.visible = true"
            />
            <span @click="dialog.visible = true">删除</span>
          </div>
        </div>
      </Form.Item>
      <Form.Item
        label="发布名称"
        name="releaseName"
        :rules="[{ required: true, validator: checkPic }]"
      >
        <a-input
          v-model:value="releaseName"
          placeholder="请输入发布名称"
          class="release-name"
          @change="releaseNameChange(releaseName.replace(/\s+/g, ''))"
        ></a-input>
        <span class="release-name-number">{{ releasenameNumber }}/50</span>
      </Form.Item>
      <Form.Item
        label="发布描述"
        name="releaseDescription"
        :rules="[{ validator: checkPic }]"
        class="form-describe"
      >
        <a-textarea
          v-model:value="describeName"
          placeholder="请输入发布描述内容"
          class="describe-name"
          @change="describeNameChange(describeName)"
        ></a-textarea>
        <span class="describe-name-number">{{ describenameNumber }}/140</span>
      </Form.Item>
      <Form.Item label="翻页时长:" name="time" :rules="[{ validator: checkPic }]" class="form-time">
        <a-input-number
          v-model:value="durationTime"
          :min="1"
          :max="timeButton === '0' ? 86400 : timeButton === '1' ? 1440 : 24"
          :precision="0"
          placeholder="请输入大于0的整数作为展示时长"
          class="time"
        ></a-input-number>
        <a-button v-if="timeButton === '0'" type="primary" @click="secondBtn">秒</a-button>
        <a-button v-else @click="secondBtn">秒</a-button>
        <a-button v-if="timeButton === '1'" type="primary" @click="minuteBtn">分</a-button>
        <a-button v-else @click="minuteBtn">分</a-button>
        <a-button v-if="timeButton === '2'" type="primary" @click="hourBtn">时</a-button>
        <a-button v-else @click="hourBtn">时</a-button>
        <div class="button-tips">
          <div>注：将信息发布到应用平台，如：动态管理，文档为固定展示，翻页时长不起作用。</div>
        </div>
      </Form.Item>
    </Form>
    <div v-if="loading" class="loadings">
      <div class="loading">
        <Spin class="loading" tip="上传中..."></Spin>
      </div>
    </div> -->
  </div>
  <!-- 清空文档 -->
  <my-dialog
    :dialog-state="dialog.visible"
    :dialog-title="dialog.title"
    :dialog-width="dialog.width"
    :icon-type="dialog.warring"
    :show-icon="true"
    :draft-box-visible="false"
    :content-text="dialog.content"
    @handleCancel="dialogCancel"
    @handleOk="dialogOk"
  ></my-dialog>
  <!-- 发布设置弹窗 -->
  <my-dialog
    :dialog-state="publishDialog.visible"
    :dialog-title="publishDialog.title"
    :dialog-width="publishDialog.width"
    :icon-type="publishDialog.default"
    :but-status="publishDialog.butStatus"
    @handleCancel="publishDialogCancel"
    @handleOk="publishDialogOk"
  >
    <template #location>
      <div class="times">
        <div class="tips">*</div>
        <div>发布时长：</div>
        <a-range-picker
          v-model:value="publishTime"
          format="YYYY-MM-DD HH:mm"
          show-time
          :disabled-time="disabledDateTime"
          :disabled-date="disabledDate"
          :disabled="[true, permanentChecked ? true : false]"
          @ok="ok"
          @openChange="openChange"
          @change="selsectTime"
          @calendarChange="onCalendarChange"
        />
      </div>
      <div v-if="permanentChecked" class="time-slot">永久</div>
      <div v-else class="time-slot">{{ timeFn }}</div>
      <div class="permanent-switch">
        <div class="permanent">永久发布：</div>
        <a-switch v-model:checked="permanentChecked" @change="isForeverChange" />
      </div>
    </template>
  </my-dialog>
  <!-- 定时发布 -->
  <regular-release-dialog
    :regular-release="regularRelease.visible"
    @handleCancel="regularReleaseCancel"
    @handleOks="regularReleaseOk"
  ></regular-release-dialog>
  <!-- 发布提示弹窗 -->
  <my-dialog
    :dialog-state="publishTipsDialog.visible"
    :dialog-title="publishTipsDialog.title"
    :dialog-width="publishTipsDialog.width"
    :icon-type="publishTipsDialog.default"
    :but-status="publishTipsDialog.butStatus"
    :btn-title="publishTipsDialog.btnTitle"
    :determine-btn="publishTipsDialog.determineBtn"
    :other-btn="true"
    class="publish-tips-dialog"
    :btn-state="publishTipsDialog.btnState"
    @handleOther="publishTipsDialogOther"
    @handleCancel="publishTipsDialogCancel"
    @handleOk="publishTipsDialogOk"
  >
    <template #location>
      <div class="content">
        <i :class="'icon-warring'" class="icon"></i>
        <span class="text">设备在所时间内正在发布以下信息</span>
      </div>
      <div class="off-line-equipment-list">
        <div v-for="(item, index) in conflictDevice" :key="item.id" class="off-line-equipment">
          <div
            v-if="item.equipmentName.length >= 5"
            class="equipment-name"
            :title="item.equipmentName"
            >{{ item.equipmentName }}</div
          >
          <div v-else class="equipment-name">{{ item.equipmentName }}</div>
          <div>
            <div
              v-for="(items, index) in item.resultCollide"
              :key="items.id"
              class="equipment-state"
            >
              <div v-if="item.resultCollide.length <= 3" class="three-list">
                <template v-if="items.releaseName.length <= 10">
                  <div>{{ items.releaseUserName }}</div>
                  <div class="names">
                    {{ items.releaseName }}
                  </div>
                </template>
                <template v-else>
                  <Popover
                    :get-popup-container="
                      triggerNode => {
                        return triggerNode.parentNode || document.body;
                      }
                    "
                    trigger="hover"
                  >
                    <template #content>
                      <div
                        v-for="itemss in item.resultCollide"
                        :key="itemss.id"
                        class="equipment-state"
                      >
                        <div class="three-list">
                          <div class="user-names">{{ itemss.releaseUserName }}</div>
                          <div style="margin-left: 15px">
                            {{ itemss.releaseName }}
                          </div>
                        </div>
                      </div>
                    </template>
                    <div class="three-list">
                      <div>{{ items.releaseUserName }}</div>
                      <div class="names">
                        {{ items.releaseName }}
                      </div>
                    </div>
                  </Popover>
                </template>
              </div>
              <Popover
                v-else
                :get-popup-container="
                  triggerNode => {
                    return triggerNode.parentNode || document.body;
                  }
                "
                trigger="hover"
              >
                <template #content>
                  <div
                    v-for="itemss in item.resultCollide"
                    :key="itemss.id"
                    class="equipment-state"
                  >
                    <div>{{ itemss.releaseUserName }}</div>
                    <div style="margin-left: 15px" class="name-style">{{ itemss.releaseName }}</div>
                  </div>
                </template>
                <div v-if="index < 3" class="three-list">
                  <div>{{ items.releaseUserName }}</div>
                  <div class="names">{{ items.releaseName }}</div>
                </div>
              </Popover>
            </div>
            <div v-if="item.resultCollide.length > 3">...</div>
          </div>
          <div class="equipment-choice" @click="choiceEquipment(index, item.equipmentId)"
            >取消选择</div
          >
        </div>
      </div>
      <div class="button-tips"> 【继续发布】将会覆盖正在发布信息的部分时段，规则如下。</div>
      <div class="button-rule">
        <div
          v-for="item in ruleList"
          :key="item.id"
          class="rule"
          :class="item.state ? 'rule-active' : null"
        >
          {{ item.name }}
        </div>
      </div>
    </template>
  </my-dialog>
</template>

<script setup>
import { timeFns } from '../../util/OBSUpload';
import MyDialog from '@/components/dialog/index.vue';
import { Upload, Form, Message, Spin, Popover } from 'ant-design-vue';
import { useRouter, useRoute } from 'vue-router';
import {
  saveInfoDocumentDraft,
  saveInfoDocument,
  getInfoDocument,
  uploadDocument,
  checkCollide,
  removeObsDocument
} from '@/api/user';

import moment from 'moment';
import { ref, onMounted, reactive, defineEmits, watch } from 'vue';
import regularReleaseDialog from '@/components/regularReleaseDialog/index.vue'; // 定时发布弹窗
import dayjs from 'dayjs';
let Base64 = require('js-base64').Base64;
const router = useRouter();
const route = useRoute();
let positionTypes = ref(); // 应用平台 ==2
onMounted(() => {
  if (route.query.state === 'device') {
    positionTypes.value = JSON.parse(Base64.decode(route.query.positionBOList))[0].positionType;
  }
  // 通过route.query.id判断是新建发布还是修改发布
  if (route.query.id) {
    editData();
  }
});
const emit = defineEmits(['getShopCode']);
let loading = ref(); // loading
/** *********************************************************弹窗相关*****************************************************************/
const publishDialog = reactive({
  // 发布设置
  title: '发布设置',
  default: 'default',
  visible: false,
  butStatus: '确认发布',
  width: '545px'
});
const dialog = reactive({
  // 清空文档
  title: '温馨提示',
  content: '是否删除该文档 ？',
  warring: 'warring',
  visible: false,
  width: '330px'
});
// 发布提示弹窗
const publishTipsDialog = reactive({
  title: '发布提示',
  default: 'default',
  visible: false,
  determineBtn: true,
  btnState: '继续发布',
  btnTitle: '返回修改',
  width: '454px'
});
const ruleList = reactive([
  {
    name: '正在发布信息',
    state: false
  },
  {
    name: '本次发布信息',
    state: true
  },
  {
    name: '正在发布信息',
    state: false
  }
]);
let conflictData = ref([]); // 冲突设备数据
// 冲突弹唱取消
function choiceEquipment(index, id) {
  conflictDevice.value.splice(index, 1);
  let data = [];
  JSON.parse(Base64.decode(route.query.positionBOList)).forEach(item => {
    if (item.positionId !== id) {
      data.push({
        positionType: item.positionType,
        equipmentTypeName: item.equipmentTypeName,
        equipmentTypeId: item.equipmentTypeId,
        name: item.name,
        positionId: item.positionId,
        funcModule: item.funcModule,
        funcModuleName: item.funcModuleName
      });
    }
  });
  conflictData.value = data;
  if (conflictData.value.length === 0) {
    publishTipsDialog.determineBtn = false;
  } else {
    publishTipsDialog.determineBtn = true;
  }
}
// 发布提示确定
function publishTipsDialogOk() {
  publishTipsDialog.visible = false;
  params.positionBOList = conflictData.value;
  saveInfoDocument(params).then(res => {
    if (res.data.code === 200) {
      Message.success('添加成功');
      router.push({
        path: '/'
      });
    }
  });
}
// 发布提示取消
function publishTipsDialogCancel() {
  publishTipsDialog.visible = false;
}
// 发布提示返回修改
function publishTipsDialogOther() {
  publishTipsDialog.visible = false;
  let data = Base64.encode(JSON.stringify(conflictData.value));
  let returnData = Base64.encode(JSON.stringify(params));
  router.push({
    path: '/position',
    query: {
      state: '设备',
      type: 'returnModify',
      data: data,
      returnData: returnData
    }
  });
}
/** *********************************************************数据区*****************************************************************/

let filePage = ref(0); // pdf转换img的数量
let currentPage = ref(1); // pdf转换img的当前页
let filePageUrl = ref(''); // pdf转换img的路径
let pageList = ref([]);
const timeButton = ref('0'); // 时分秒
const coverFileList = ref([]); // 文档List
const releasenameNumber = ref(0); // 发布名字数量
const describenameNumber = ref(0); // 描述数量
const releaseName = ref(''); // 发布名称
const durationTime = ref(10); // 展示时间
const describeName = ref(''); // 描述内容
const uploadData = reactive({}); // 上传的数据
// 参数
let params = reactive({
  infoBO: {
    infoDesc: '',
    infoDuration: '',
    infoName: '',
    infoTimeType: '',
    // infoState: 0, // 发布信息状态 0发布中 1待生效 2已撤回 3已结束
    isDraft: 0, // 0非草稿 1草稿
    infoType: 2, // 0视频 1组图 2文档 3文章
    thumbnailUrl: '', // 封面
    isForever: 0, // 0非永久 1永久
    releaseOpportunityType: null, // 普通发布0  定时发布天1； 定时发布周2； 草稿箱null
    documentBO: {
      infoDocumentUrl: '',
      documentMd5: '',
      fileFormat: '',
      filePage: '',
      fileSize: ''
    },
    validPeriodStart: '',
    validPeriodStop: ''
  }
});
let publishTime = ref([dayjs(moment().format('YYYY-MM-DD HH:mm')), '']); // 发布设置弹窗时间
let permanentChecked = ref(false); // 永久发布switch状态
let publishStartDate = ref(''); // 发布设置弹窗开始时间
let publishEndDate = ref(''); // 发布设置弹窗结束时间
let timeFn = ref('0天0时0秒');

/** *********************************************************方法区域*****************************************************************/
// 离开就提示
// 发布名称
watch(releaseName, (newName, oldName) => {
  if (route.query.id) {
    if (newName === compareReleaseName.value) {
      emit('getShopCode', '');
    } else {
      emit('getShopCode', newName);
    }
  } else {
    if (newName.length > 0) {
      emit('getShopCode', newName);
    } else {
      emit('getShopCode', '');
    }
  }
});
// 发布描述
watch(describeName, (newName, oldName) => {
  if (route.query.id) {
    if (newName === compareDescribeName.value) {
      emit('getShopCode', '');
    } else {
      emit('getShopCode', newName);
    }
  } else {
    if (newName.length > 0) {
      emit('getShopCode', newName);
    } else {
      emit('getShopCode', '');
    }
  }
});
// 上传文档
watch(coverFileList, (newName, oldName) => {
  if (route.query.id) {
    if (newName === compareUploadData.value) {
      emit('getShopCode', []);
    } else {
      emit('getShopCode', 'asdasda');
    }
  } else {
    if (newName.length > 0) {
      emit('getShopCode', newName);
    } else {
      emit('getShopCode', []);
    }
  }
});
// 发布时长
watch(durationTime, (newName, oldName) => {
  if (route.query.id) {
    if (newName === compareDurationTime.value) {
      emit('getShopCode', '');
    } else {
      emit('getShopCode', newName);
    }
  } else {
    if (newName !== compareDurationTime.value) {
      emit('getShopCode', newName);
    } else {
      emit('getShopCode', '');
    }
  }
});
//  禁用当前时间之前的时间
function disabledDate(current) {
  return current && current < moment().subtract(1, 'days').endOf('day');
}

// 当日只能选择当前时间之后的时间点
const range = (start, end) => {
  const result = [];
  for (let i = start; i <= end; i++) {
    result.push(i);
  }
  return result;
};
const newS = ref('');
const currentTimes = ref('');
// 禁止当前时间之前的时间不可选
const disabledDateTime = (dates, partial) => {
  if (dates != null) {
    newS.value = moment(dates.$d).format('YYYY-MM-DD'); // 选择的时间
    currentTimes.value = moment(dates.$d).format('YYYY-MM-DD HH'); // 选择的时间
  }
  let currentTime = moment().format('YYYY-MM-DD'); // 当前时间
  let hours = moment().hours(); // 0~23
  let minutes = moment().minutes(); // 0~59
  let seconds = moment().seconds(); // 0~59
  if ((dates === null && partial === 'end') || newS.value === currentTime) {
    return {
      disabledHours: () => range(0, hours - 1),
      disabledMinutes: () => (currentTimes.value.slice(-2) <= hours ? range(0, minutes) : null),
      disabledSeconds: () => range(0, seconds - 1)
    };
  }
};
// 时间确认事件
function ok(date) {
  timeFn.value = timeFns(date[0], date[1]);
  let newS = moment(publishTime.value[1].$d).format('YYYY-MM-DD HH:mm'); // 选择的时间
  let currentDate = moment().format('YYYY-MM-DD HH:mm');
  if (newS <= currentDate) {
    Message.error('结束时间不能小于等于开始时间,请重新选择结束时间');
    publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), null];
    publishEndDate.value = '';
    timeFn.value = '0天0时0秒';
  }
}

// 时间框事件
function openChange(e) {
  if (e) {
    publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
    publishStartDate.value = moment().format('YYYY-MM-DD HH:mm');
  } else {
    if (publishEndDate.value === '') {
      publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
    } else {
      publishTime.value = [
        dayjs(moment().format('YYYY-MM-DD HH:mm')),
        dayjs(publishEndDate.value, 'YYYY-MM-DD HH:mm')
      ];
    }
  }
}
function selsectTime(date, dateString) {
  publishStartDate.value = dateString[0];
  publishEndDate.value = dateString[1];
}
// 时间取消事件
function onCalendarChange() {
  timeFn.value = '0天0时0秒';
}
// 永久change
function isForeverChange() {
  if (permanentChecked.value) {
    publishTime.value = [
      dayjs(moment().format('YYYY-MM-DD HH:mm')),
      dayjs('9999-12-31 23:59', 'YYYY-MM-DD HH:mm')
    ];
  } else {
    publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
    timeFn.value = '0天0时0秒';
  }
  publishEndDate.value = '';
}
// 发布设置取消按钮
function publishDialogCancel() {
  publishDialog.visible = false;
  permanentChecked.value = false;
  publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
}
// 发布设置确定
function publishDialogOk() {
  if (permanentChecked.value === false && publishEndDate.value === '') {
    Message.error('时长不能为空');
    return;
  }
  let equipmentIdList = []; // 设备id 集合
  JSON.parse(Base64.decode(route.query.positionBOList)).forEach(item => {
    equipmentIdList.push(item.positionId);
  });
  // 发布设备冲突参数
  let releaseParamss = {
    validPeriodStart: moment().format('YYYY-MM-DD HH:mm:ss'),
    validPeriodStop:
      publishEndDate.value.length === 16 ? publishEndDate.value + ':00' : publishEndDate.value,
    equipmentIdList: equipmentIdList,
    opportunityType: 0,
    isForever: permanentChecked.value ? 1 : 0
  };
  if (permanentChecked.value) {
    releaseParamss.validPeriodStop = '9999-12-31 23:59:59';
    params.infoBO.validPeriodStop = '9999-12-31 23:59:59';
  } else {
    params.infoBO.validPeriodStop =
      publishEndDate.value.length === 16 ? publishEndDate.value + ':00' : publishEndDate.value;
  }
  // 发布参数
  params.infoBO.validPeriodStart = moment().format('YYYY-MM-DD HH:mm:ss');
  params.infoBO.isForever = permanentChecked.value ? 1 : 0;
  params.positionBOList = JSON.parse(Base64.decode(route.query.positionBOList)); // 位置信息
  conflictData.value = JSON.parse(Base64.decode(route.query.positionBOList));
  params.infoBO.infoName = releaseName.value.replace(/\s+/g, ''); // 发布名称
  params.infoBO.thumbnailUrl = pageList.value[0].url;
  params.infoBO.infoDesc = describeName.value; // 描述
  params.infoBO.infoTimeType = timeButton.value; // 时分秒
  params.infoBO.infoDuration = durationTime.value; // 展示时间
  params.infoBO.documentBO = uploadData.value; // Md5数据
  params.infoBO.releaseOpportunityType = 0; // 普通发布0  定时发布1
  if (params.positionBOList[0].positionType === 2) {
    saveInfoDocument(params).then(res => {
      if (res.data.code === 200) {
        Message.success('保存草稿成功');
        router.push({
          path: '/'
        });
      }
    });
  } else {
    checkCollide(releaseParamss).then(res => {
      // 未返回数据 代表没有冲突设备
      if (res.data.data.length === 0) {
        saveInfoDocument(params).then(res => {
          if (res.data.code === 200) {
            Message.success('保存草稿成功');
            router.push({
              path: '/'
            });
          }
        });
      } else {
        // 打开设备冲突 弹窗
        conflictDevice.value = res.data.data;
        publishTipsDialog.visible = true;
      }
    });
  }
  publishDialog.visible = false;
  permanentChecked.value = false;
  publishTime.value = [dayjs(moment().format('YYYY-MM-DD HH:mm')), ''];
}
// 定时发布状态
let regularRelease = ref({
  visible: false
});
// 定时发布取消按钮
function regularReleaseCancel() {
  regularRelease.value.visible = false;
}
let conflictDevice = ref([]); // 冲突设备list
// 确定定时发布
function regularReleaseOk(data) {
  if (data.isForever === false) {
    if (data.validPeriodStart.value === '' || data.validPeriodStop.value === '') {
      Message.warning('请选择有效期限');
      return;
    }
    if (data.releaseFrequency === 0) {
      if (data.daySiteBOList[0].newStartTime === '' || data.daySiteBOList[0].newStopTime === '') {
        Message.warning('至少选择一个发布时间');
        return;
      }
    } else {
      if (
        data.weekSiteBOList[0].daySiteBOList[0].newStartTime === '' ||
        data.weekSiteBOList[0].daySiteBOList[0].newStopTime === ''
      ) {
        Message.warning('至少选择一个发布时间');
        return;
      }
    }
  } else {
    if (data.releaseFrequency === 0) {
      if (data.daySiteBOList[0].newStartTime === '' || data.daySiteBOList[0].newStopTime === '') {
        Message.warning('至少选择一个发布时间');
        return;
      }
    } else {
      if (
        data.weekSiteBOList[0].daySiteBOList[0].newStartTime === '' ||
        data.weekSiteBOList[0].daySiteBOList[0].newStopTime === ''
      ) {
        Message.warning('至少选择一个发布时间');
        return;
      }
    }
  }
  let equipmentIdList = []; // 设备id 集合
  JSON.parse(Base64.decode(route.query.positionBOList)).forEach(item => {
    equipmentIdList.push(item.positionId);
  });
  // 定时发布设备冲突参数
  let timeParams = {
    validPeriodStart: data.validPeriodStart,
    validPeriodStop: data.validPeriodStop,
    equipmentIdList: equipmentIdList,
    opportunityType: 1,
    isForever: permanentChecked.value ? 1 : 0,
    frequency: data.releaseFrequency, // 频率 0 天 1 周
    byWeekList: data.releaseFrequency === 1 ? data.weekSiteBOList : [], // 周
    byDayList: data.releaseFrequency === 0 ? data.daySiteBOList : [] // 天
  };
  params.infoBO.validPeriodStart = data.validPeriodStart; // 有效期开始
  params.infoBO.validPeriodStop = data.validPeriodStop; // 有效期结束
  params.infoBO.isForever = data.isForever ? 1 : 0; // 0非永久 1永久
  params.infoBO.releaseOpportunityType = data.releaseFrequency === 0 ? 1 : 2; // 普通发布0  定时发布天1； 定时发布周2； 草稿箱null
  params.infoBO.releaseFrequency = data.releaseFrequency; // 发布频率 0每天 1每周
  if (data.releaseFrequency === 0) {
    params.infoBO.daySiteBOList = data.daySiteBOList; // 按天发布 数组
  } else {
    params.infoBO.weekSiteBOList = data.weekSiteBOList; // 按周的定时发布 数组
  }
  params.positionBOList = JSON.parse(Base64.decode(route.query.positionBOList));
  conflictData.value = JSON.parse(Base64.decode(route.query.positionBOList));
  params.infoBO.infoName = releaseName.value.replace(/\s+/g, '');
  params.infoBO.thumbnailUrl = pageList.value[0].url;
  params.infoBO.infoDesc = describeName.value;
  params.infoBO.infoTimeType = timeButton.value;
  params.infoBO.infoDuration = durationTime.value;
  params.infoBO.documentBO = uploadData.value; // Md5数据
  checkCollide(timeParams).then(res => {
    // 未返回数据 代表没有冲突设备
    if (res.data.data.length === 0) {
      saveInfoDocument(params).then(res => {
        if (res.data.code === 200) {
          Message.success('保存草稿成功');
          router.push({
            path: '/'
          });
        }
      });
    } else {
      // 打开设备冲突 弹窗
      conflictDevice.value = res.data.data;
      publishTipsDialog.visible = true;
    }
  });
  regularRelease.value.visible = false;
}
let createTime = ref(''); // 返回的创建时间
// 按设备->组图
function onPublic(value) {
  if (coverFileList.value.length === 0) {
    Message.warning('文档内容不能为空');
    return;
  }
  if (releaseName.value.replace(/\s+/g, '') === '') {
    Message.warning('发布名称不能为空');
    return;
  }
  if (value === 1) {
    publishDialog.visible = true;
  } else if (value === 2) {
    regularRelease.value.visible = true;
  } else if (value === 'to') {
    params.infoBO.infoName = releaseName.value.replace(/\s+/g, '');
    params.infoBO.infoDesc = describeName.value;
    params.infoBO.infoTimeType = timeButton.value;
    params.infoBO.infoDuration = durationTime.value;
    params.infoBO.thumbnailUrl = pageList.value[0].url;
    params.infoBO.documentBO = uploadData.value;
    params.infoBO.pushTime = createTime.value; // 创建时间
    params.oldPositionBOList = oldPositionBOList.value;
    if (route.query.state === '编辑') {
      params.infoBO.id = route.query.id;
      params.infoBO.isForever = isForever.value;
      params.infoBO.releaseOpportunityType = releaseOpportunityType.value; // releaseOpportunityType null 0 1 2
      params.infoBO.validPeriodStart = validPeriodStart.value; // 开始时间
      params.infoBO.validPeriodStop = validPeriodStop.value; // 结束时间
      params.weekSiteVOList = weekSiteVOList.value; // 发布时间-周
      params.daySiteVOList = daySiteVOList.value; // 发布时间-天
      let data = Base64.encode(JSON.stringify(params));
      router.push({
        path: '/position',
        query: {
          data: data,
          state: '编辑',
          releaseType: 100
        }
      });
    } else {
      let data1 = Base64.encode(JSON.stringify(params));
      router.push({
        path: '/position',
        query: {
          data: data1,
          state: route.query.state,
          type: '文档',
          releaseType: 100
        }
      });
    }
  } else {
    if (value === 3) {
      params.positionBOList = JSON.parse(Base64.decode(route.query.positionBOList));
    }
    params.infoBO.infoName = releaseName.value;
    params.infoBO.infoDesc = describeName.value;
    params.infoBO.infoTimeType = timeButton.value;
    params.infoBO.infoDuration = durationTime.value;
    params.infoBO.documentBO = uploadData.value;
    params.infoBO.isDraft = 1;
    params.infoBO.thumbnailUrl = pageList.value[0].url;
    if (route.query.state === '草稿箱修改') {
      params.infoBO.id = route.query.id;
    }
    saveInfoDocumentDraft(params).then(res => {
      if (res.data.code === 200) {
        Message.success('保存草稿成功');
        router.push({
          path: '/'
        });
      }
    });
  }
}
// 清空文档弹窗取消
function dialogCancel() {
  dialog.visible = false;
}
// 清空文档确认事件
function dialogOk() {
  if (!route.query.id) {
    removeObsDocument({
      infoDocumentUrl: deleteInfoDocumentUrl.value,
      filePage: deleteFilePage.value
    }).then(res => {
      if (res.data.code === 200) {
        coverFileList.value = [];
        pageList.value = [];
        filePage.value = 0; // pdf转换img的数量
        currentPage.value = 1;
      } else {
        Message.error('清除文档失败！');
      }
    });
  } else {
    coverFileList.value = [];
    pageList.value = [];
    filePage.value = 0; // pdf转换img的数量
    currentPage.value = 1;
  }
  dialog.visible = false;
}
function secondBtn() {
  timeButton.value = '0';
}
function minuteBtn() {
  timeButton.value = '1';
  if (durationTime.value > 1440) {
    durationTime.value = 1440;
  }
}
function hourBtn() {
  timeButton.value = '2';
  if (durationTime.value > 24) {
    durationTime.value = 24;
  }
}
let oldPositionBOList = ref([]); // 位置信息
let isForever = ref(); // 永久状态
let releaseOpportunityType = ref(); //
let validPeriodStart = ref();
let validPeriodStop = ref();
let weekSiteVOList = ref([]); // 定时发布时间/周
let daySiteVOList = ref([]); // 定时发布时间/天
let compareReleaseName = ref(''); // 比较名称
let compareDescribeName = ref(''); // 比较发布描述
let compareUploadData = ref([]); // 比较上传附件
let compareDurationTime = ref(''); // 比较翻页时长
// 编辑详情
function editData() {
  coverFileList.value.length = 1;
  getInfoDocument(route.query.id).then(res => {
    let data = res.data.data;
    isForever.value = data.infoVO.isForever;
    filePage.value = data.documentVO.filePage;
    let dataList = [];
    let index = data.documentVO.infoDocumentUrl.lastIndexOf('.');
    let pdfImg = data.documentVO.infoDocumentUrl.substring(0, index);

    let urlFirst = data.documentVO.infoDocumentUrl.substring(
      0,
      data.documentVO.infoDocumentUrl.lastIndexOf('.')
    );
    let firstUrl =
      process.env.VUE_APP_PROJECT_URL === 'https://www.jnshiyanqu.cn/gateway/'
        ? data.documentVO.infoDocumentUrl.substring(0, 87)
        : data.documentVO.infoDocumentUrl.substring(0, 89);
    let name =
      process.env.VUE_APP_PROJECT_URL === 'https://www.jnshiyanqu.cn/gateway/'
        ? urlFirst.slice(87)
        : urlFirst.slice(89);

    filePageUrl.value = firstUrl + encodeURIComponent(name);
    for (let index = 0; index < data.documentVO.filePage; index++) {
      let i = index + 1;
      dataList.push({
        state: false,
        url: firstUrl + encodeURIComponent(name) + '/' + i + '.jpg'
      });
    }
    uploadData.value = data.documentVO;
    // 编辑赋值
    releaseName.value = data.infoVO.infoName; // 名称
    compareReleaseName.value = data.infoVO.infoName; // 比较名称
    describeName.value = data.infoVO.infoDesc;
    compareDescribeName.value = data.infoVO.infoDesc; // 比较发布描述
    durationTime.value = data.infoVO.infoDuration;
    compareDurationTime.value = data.infoVO.infoDuration; // 比较翻页时长
    compareUploadData.value = data.documentVO; // 比较上传附件
    describenameNumber.value = describeName.value.length;
    releasenameNumber.value = releaseName.value.length;
    timeButton.value = String(data.infoVO.infoTimeType);
    pageList.value = dataList;
    pageList.value[0].state = true;
    oldPositionBOList.value = data.positionVOList; // 位置信息
    releaseOpportunityType.value = data.infoVO.releaseOpportunityType;
    validPeriodStart.value = data.infoVO.validPeriodStart;
    validPeriodStop.value = data.infoVO.validPeriodStop;
    oldPositionBOList.value = data.positionVOList; // 位置信息
    weekSiteVOList.value = data.weekSiteVOList; // 发布时间/周
    daySiteVOList.value = data.daySiteVOList; // 发布时间/天
    createTime.value = data.infoVO.createTime; // 创建时间
  });
}
// 发布内容
function releaseNameChange(value) {
  if (value.length > 50) {
    releaseName.value = value.substring(0, 50);
    releasenameNumber.value = 50;
  } else {
    releasenameNumber.value = value.length;
  }
}
// 描述内容
function describeNameChange(value) {
  if (value.length > 140) {
    describeName.value = value.substring(0, 140);
    describenameNumber.value = 140;
  } else {
    describenameNumber.value = value.length;
  }
}
// 分页减
function pageReduce(item) {
  pageList.value.forEach(item => {
    item.state = false;
  });
  currentPage.value = item;
  pageList.value[item - 1].state = true;
}
// 分页加
function pageAdd(item) {
  pageList.value.forEach(item => {
    item.state = false;
  });
  pageList.value[item + 1].state = true;
  currentPage.value = item + 2;
}
// 必选项
const checkPic = (rule, value) => {};
// 上传视频移除
function deleteFiles() {
  coverFileList.value.splice(0, 1);
}
function customRequest(file) {
  let fileName = file.file.name;
  let uid = file.file.uid;
  let pos = fileName.lastIndexOf('.');
  let name = fileName.substring(0, fileName.lastIndexOf('.'));
  let lastName = fileName.substring(pos, fileName.length);
  if (name.length > 50) {
    file.file['status'] = 'error';
    file.file['response'] = '附件名超出字符限制，请修改后重新上传!';
    Message.error('附件名超出字符限制，请修改后重新上传!');
    file.pop();
  } else if (file.file.size / 1024 / 1024 > 50) {
    file.file['status'] = 'error';
    file.file['response'] = '文件大小超出上传限制!';
    Message.error('文件大小超出上传限制!');
    file.pop();
  } else if (file.file.size === 0) {
    file.file['status'] = 'error';
    file.file['response'] = '文件大小不能为0KB!';
    Message.error('文件大小不能为0KB!');
    file.pop();
  } else if (lastName.toLowerCase() !== '.pdf') {
    file.file['status'] = 'error';
    file.file['response'] = '只支持.pdf格式!';
    Message.error('只支持pdf格式');
    file.pop();
  } else {
    file.file['status'] = 'done';
    getUploadDocument(file);
  }
}
let deleteInfoDocumentUrl = ref(''); // 文档地址。删除使用
let deleteFilePage = ref(''); // 文档页数。删除使用
function getUploadDocument(file) {
  let formData = new FormData();
  formData.append('file', file.file);
  loading.value = true;
  let timer = setTimeout(() => {
    loading.value = false;
    Message.error('上传失败！');
    coverFileList.value = [];
  }, 30000);
  uploadDocument(formData).then(res => {
    if (res.data.code === 200) {
      clearTimeout(timer);
      let data = res.data.data;
      deleteInfoDocumentUrl.value = data.infoDocumentUrl;
      deleteFilePage.value = data.filePage;
      loading.value = false;
      filePage.value = data.filePage;
      let dataList = [];

      let urlFirst = data.infoDocumentUrl.substring(0, data.infoDocumentUrl.lastIndexOf('.'));
      let firstUrl =
        process.env.VUE_APP_PROJECT_URL === 'https://www.jnshiyanqu.cn/gateway/'
          ? data.infoDocumentUrl.substring(0, 87)
          : data.infoDocumentUrl.substring(0, 89);
      let name =
        process.env.VUE_APP_PROJECT_URL === 'https://www.jnshiyanqu.cn/gateway/'
          ? urlFirst.slice(87)
          : urlFirst.slice(89);
      let index = data.infoDocumentUrl.lastIndexOf('.');
      let pdfImg = data.infoDocumentUrl.substring(0, index);
      filePageUrl.value = firstUrl + encodeURIComponent(name);
      for (let index = 0; index < data.filePage; index++) {
        let i = index + 1;
        dataList.push({
          state: false,
          url: firstUrl + encodeURIComponent(name) + '/' + i + '.jpg'
        });
      }
      pageList.value = dataList;
      pageList.value[0].state = true;
      uploadData.value = res.data.data;
    } else {
      loading.value = false;
      Message.error('上传失败！');
      coverFileList.value = [];
    }
  });
}
// 上传文档Change
function handleChange({ fileList }) {
  fileList.map((item, index) => {
    if (item.size / 1024 / 1024 > 50) {
      item['status'] = 'error';
      item['response'] = '文件大小不能超过50M!';
      coverFileList.value.splice(index, 1);
    } else {
      item['status'] = 'done';
    }
    return item;
  });
  coverFileList.value = fileList;
}
</script>
<style lang="less" scoped>
.no-kaifa {
  text-align: center;
  margin: 186.5px 0px;
  img {
    margin: auto;
    width: 300px;
    height: 300px;
  }
  span {
    font-size: 14px;
    font-family: Source Han Sans CN, Source Han Sans CN-Regular;
    font-weight: 400;
    text-align: LEFT;
    color: #999999;
  }
}
.times {
  display: flex;
  align-items: center;
  /deep/ .micro-ant-picker-range {
    width: 391px !important;
  }
  .tips {
    color: #ff0000;
    margin-right: 8px;
  }
  /deep/ .ant-picker-input > input {
    text-align: center !important;
  }
}
.time-slot {
  display: flex;
  justify-content: flex-end;
  margin-right: 23px;
  margin-top: 8px;
  font-size: 14px;
  color: #999999;
}
.permanent-switch {
  display: flex;
  margin-top: 25px;
  align-items: center;
  .permanent {
    display: flex;
    align-items: center;
    margin-right: 10px;
  }
}
.exhibition-Pdf-box {
  width: 65%;
  max-height: 1264px;
  min-height: 529px;
  padding: 16px;
  background: #f8f8f8;
  border: 1px dashed #e1dddd;
  border-radius: 5px;
  overflow: auto;
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-thumb {
    background: rgba(20, 20, 20, 0.2);
    border-radius: 3px;
  }
  &::-webkit-scrollbar-track {
    background: transparent;
  }
  .exhibition-Pdf {
    border-radius: 5px;
    .pdf-img {
      width: 844px;
      max-height: 100%;
      min-height: 460px;
    }
    .pager {
      display: flex;
      margin: auto;
      margin-top: 16px;
      .number {
        font-size: 14px;
        font-family: Source Han Sans CN, Source Han Sans CN-Regular;
        font-weight: 400;
        color: #666666;
        margin: 0 24px;
      }
      .prohibit {
        cursor: no-drop !important;
      }
      .pager-left,
      .pager-right {
        cursor: pointer;
        width: 20px;
        height: 20px;
        background: #e1dddd;
        border-radius: 50%;
        i {
          margin: 3px;
        }
      }
    }
  }
}
.car {
  display: flex;
}
.delete {
  cursor: pointer;
  display: flex;
  position: absolute;
  bottom: 16px;
  left: 806px;
  font-size: 14px;
  align-items: end;
  img {
    margin-right: 7.14px;
    width: 14px;
    height: 15px;
    margin-bottom: 4px;
  }
  font-size: 14px;
  color: #999999;
}
/deep/ .micro-ant-upload-select-picture-card {
  margin-top: 0px !important;
}
/deep/.micro-ant-upload.micro-ant-upload-select-picture-card {
  background: #ffffff;
}
/deep/ .micro-ant-upload {
  width: 320px !important;
  height: 180px !important;
}
/deep/ .ant-upload-picture-card-wrapper {
  min-height: 180px;
  max-height: 414px;
  width: 320px;
}
/deep/ .ant-upload-list-picture-card-container {
  height: 180px;
  width: 320px;
  background: #ffffff !important;
}
.ant-upload-list {
  display: flex;
  flex-wrap: wrap;
  overflow-y: auto;
  max-height: 414px;
  width: 1360px;
}
.ant-upload-list {
  .ant-upload-list-picture .ant-upload-list-item-error {
    border-color: #fff !important;
  }
  .ant-upload-list-item-name {
    color: #222222;
  }
}
.ant-upload-list-item-card-actions {
  right: 14px;
}
.ant-upload-list-item-error .ant-upload-list-item-card-actions .anticon {
  color: #999;
}
.upload-icon {
  margin: auto;
  margin-bottom: 16px;
}
// 注释原因：解决附件上传 样式爆红并有弹窗的问题
// .ifont-wid-Upload_icon_restart:active {
//   color: red;
// }
.title {
  .left-title {
    width: 3px;
    height: 16px;
    background: #d6aa56;
    border-radius: 4px;
    position: absolute;
    margin-right: 8px;
    margin-top: 13px;
    top: -8px;
  }
  position: relative;
  line-height: 26px;
  color: #222222;
  font-size: 18px;
  font-weight: 500;
  .title-coutent {
    margin-left: 8px;
  }
}
.next-button {
  margin: 24px 0 14px;
  display: flex;
  justify-content: flex-end;
  .next {
    background: #d6aa56;
    width: 74px;
    color: #fff;
    border-radius: 4px;
    border: 1px solid #d6aa56;
  }
  .save {
    width: 88px;
    border: 1px solid #d6aa56;
    background: #fff;
    color: #d6aa56;
    border-radius: 4px;
    margin-left: 16px;
  }
}
.uplod {
  margin-top: 8px;
  background: #f8f8f8;
  border-radius: 4px;
  padding: 16px 24px 16px 16px;
  .up-head {
    display: flex;
    align-items: center;
    line-height: 24px;
  }
}
.form {
  margin-top: 16px;
  /deep/ .ant-upload {
    width: 320px !important;
    height: 180px !important;
    border: 1px dashed #e1dddd !important;
    border-radius: 5px;
    margin-top: 32px;
  }
  .tip {
    color: #999999;
    font-size: 12px;
  }
  .release-name {
    width: 65%;
    height: 40px;
    background: #ffffff;
    border: 1px solid #e1dddd;
    border-radius: 4px;
    position: relative;
  }
  .release-name-number {
    position: absolute;
    top: 10px;
    left: 60%;
    color: #c2c2c2;
  }
  .form-describe {
    margin-left: 11px;
    .describe-name {
      width: 65%;
      max-height: 224px;
      min-height: 224px;
      background: #ffffff;
      border: 1px solid #d5dae1;
      border-radius: 6px;
    }
    .describe-name-number {
      position: absolute;
      top: 200px;
      left: 59.5%;
      color: #c2c2c2;
    }
  }
  .form-time {
    margin-left: 11px;
    .time {
      width: 352px;
      height: 40px;
      background: #ffffff;
      border: 1px solid #e1dddd;
      border-radius: 4px;
    }

    .ant-input-number-input {
      height: 40px;
    }
    .button-tips {
      font-size: 14px;
      color: #999999;
      div {
        margin-top: 8px;
      }
    }
    button {
      margin-left: 16px;
    }
  }
}
/deep/ .micro-ant-input-number:focus {
  box-shadow: 0 0 0 1px #d6aa56 !important;
}
/deep/ .micro-ant-input-number-input {
  height: 40px !important;
}
/deep/ .micro-ant-input:hover {
  border-color: #d6aa56 !important;
}
.upload-list-inline :deep(.ant-upload-list-item) {
  float: left;
  width: 200px;
  margin-right: 8px;
}
.ant-upload-list-picture-card .ant-upload-list-item {
  width: 320px !important;
  height: 180px !important;
}
.upload-list-inline :deep(.ant-upload-animate-enter) {
  animation-name: uploadAnimateInlineIn;
}
.upload-list-inline :deep(.ant-upload-animate-leave) {
  animation-name: uploadAnimateInlineOut;
}
.form .ant-upload {
  margin-top: 0px;
  display: block;
  width: 320px !important;
  height: 180px !important;
}
.upload-title {
  display: flex;
  align-items: center;
}
.publish-tips-dialog {
  .content {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    .icon {
      display: block;
      width: 20px;
      height: 20px;
      margin: 5px 10px 0 0;
    }
    .icon-warring {
      background: url('../../assets/icons/images/exclamation_icon_circle.png') no-repeat center;
      background-size: 100% 100%;
    }
  }
  .button-tips {
    font-size: 12px;
    color: #999999;
  }
  .three-list {
    display: flex;
  }
  .off-line-equipment-list {
    .equipment-name {
      width: 92px;
      overflow: hidden;
      white-space: nowrap;
      /*文字超出宽度则显示ellipsis省略号*/
      text-overflow: ellipsis;
    }
    .off-line-equipment {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 5px 14px;
      width: 406px;
      max-height: 110px;
      background: #f8f8f8;
      border-radius: 4px;
      margin-bottom: 8px;
      .equipment-state {
        display: flex;
        align-items: center;
        .line {
          margin-right: 4px;
          width: 8px;
          height: 8px;
          background: #999999;
          border-radius: 50%;
        }
        .names {
          width: 150px;
          overflow: hidden;
          white-space: nowrap;
          margin-left: 10px;
          text-overflow: ellipsis;
        }
        // .namess {
        //   margin-left: 10px;
        //   width: 190px;
        //   overflow: hidden;
        //   white-space: nowrap;
        //   text-overflow: ellipsis;
        // }
      }
      .equipment-choice {
        cursor: pointer;
        width: 80px;
        text-align: center;
        line-height: 24px;
        height: 24px;
        background: #ffffff;
        font-size: 14px;
        color: #d6aa56;
        border: 1px solid #d6aa56;
        border-radius: 4px;
      }
    }
  }
  .time {
    display: flex;
    align-items: center;
    /deep/ .micro-ant-picker-range {
      width: 391px !important;
    }
    .tips {
      color: #ff0000;
      margin-right: 8px;
    }
    /deep/ .ant-picker-input > input {
      text-align: center !important;
    }
  }
  .button-rule {
    margin-top: 16px;
    cursor: pointer;
    display: flex;
    align-items: center;
    width: 406px;
    height: 30px;
    background: rgba(214, 170, 86, 0.2);
    border-radius: 4px;
    .rule {
      font-size: 14px;
      width: 135px;
      text-align: center;
      color: #d6aa56;
    }
    .rule-active {
      background: #d6aa56;
      color: #ffffff !important;
      text-align: center;
      line-height: 30px;
      width: 135px;
      height: 30px;
    }
  }
}
.loadings {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
}
.loading {
  margin-left: 19%;
  margin-top: 14%;
}
.file-box {
  position: relative;
}
/deep/ .micro-ant-popover-inner-content {
  padding: 12px 16px;
  max-height: 220px;
  width: 467px !important;
  overflow: auto;
}
.name-style {
  width: 361px;
}
/deep/ .micro-ant-btn-primary:hover {
  color: #fff !important;
}
</style>
